r = defaultdict(lambda: 0.1)


def score3(book):
	return sum([float(k*book[k])/float(sum(book.values())) for k in [1,2,3,4,5]])

def add_vectors(vec1, vec2):
	target = Counter()
	all_words = set(vec1.keys()) | set(vec2.keys())
	for word in all_words:
		target[word] = (vec1[word] + vec2[word]) / float(2.0)
	return target


def merge_vectors(vectors):
	all_words = set()
	target = Counter()
	for vector in vectors:
		all_words = all_words | set(vector.keys())
	for word in all_words:
		for vector in vectors:
			target[word] += vector[word] / float(len(vectors))
	return target


def merge(vectors):
	target = Counter()
	for vector in vectors:
		target += vector
	for word in target:
		target[word] = target[word] / float(len(vectors))
	return target

def get_cosine(vec1, vec2):
	intersection = set(vec1.keys()) & set(vec2.keys())
	numerator = sum([vec1[x] * vec2[x] for x in intersection])
	sum1 = sum([vec1[x]**2 for x in vec1.keys()])
	sum2 = sum([vec2[x]**2 for x in vec2.keys()])
	denominator = math.sqrt(sum1) * math.sqrt(sum2)
	if not denominator:
		return 0.0
	else:
		return float(numerator) / denominator




ll = [Counter(["a","b","c","a"]), Counter(["b","c"]), Counter(["c","d","e"])]


struct = defaultdict(lambda: defaultdict(list))

struct["someuser"][5].append("book")
#for (user,book,rating) in ratings:
#	struct[user][rating].append(book)

for user in struct.keys():
	for rating in [1,2,3,4,5]:
		for book in struct[user][rating]:
			print user, rating, book



def get_score(user,book):
	for rating in [1,2,3,4,5]:
		similarities[rating] = get_cosine(merge(struct[user][rating]), book)
	return score3(similarities)







